<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="教材名称" prop="textbookName">
        <el-input
          v-model="queryParams.textbookName"
          placeholder="请输入教材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:textbook:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:textbook:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:textbook:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:textbook:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="textbookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教材ID" align="center" prop="id" />
      <el-table-column label="教材名称" align="center" prop="textbookName" />
      <el-table-column label="教材图片" align="center" prop="coverImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="教材作者" align="center" prop="author" />
      <el-table-column label="出版社" align="center" prop="publisher" />
      <el-table-column label="教材价格" align="center" prop="price" />
      <el-table-column label="教材类型" align="center" prop="textbookType" />
      <el-table-column label="教材简介" align="center" prop="introduction" />
      <el-table-column label="教材状态" align="center" prop="isOnSale">
      <template slot-scope="scope">
        <span>{{ scope.row.isOnSale === 0 ? '下架' : '上架' }}</span>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:textbook:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:textbook:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-shopping-cart-2"
            @click="handleBuy(scope.row)"
            v-hasPermi="['manage:textbook:list']"
          >购买</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="handleViewReviews(scope.row)"
            v-hasPermi="['manage:textbook:list']"
          >查看评论</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教材列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教材名称" prop="textbookName">
          <el-input v-model="form.textbookName" placeholder="请输入教材名称" />
        </el-form-item>
        <el-form-item label="教材作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入教材作者" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="教材价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入教材价格" />
        </el-form-item>
        <el-form-item label="教材类型" prop="textbookType">
          <el-input v-model="form.textbookType" placeholder="请输入教材类型" />
        </el-form-item>
        <el-form-item label="教材简介" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教材图片" prop="coverImage">
          <image-upload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="教材状态" prop="isOnSale">
          <el-select v-model="form.isOnSale" placeholder="请选择教材状态">
            <el-option label="下架" value="0"></el-option>
            <el-option label="上架" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看评论对话框 -->
    <el-dialog :title="`教材评论 (${currentTextbookName})`" :visible.sync="reviewDialogVisible" width="600px" append-to-body>
      <el-table :data="reviews" style="width: 100%">
        <el-table-column prop="userId" label="评论人ID" width="150"/>
        <el-table-column prop="reviewText" label="评论内容"/>
        <el-table-column prop="reviewTime" label="评论时间" width="180"/>
        <el-table-column prop="rating" label="评分" width="100"/>
      </el-table>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog :title="`订单详情`" :visible.sync="orderDialogVisible" width="500px">
        <el-form ref="orderForm" :model="orderForm" label-width="80px">
            <el-form-item label="教材图片">
                <image-preview :src="orderForm.coverImage" :width="100" :height="100"/>
            </el-form-item>
            <el-form-item label="教材名称">
                <span>{{ orderForm.textbookName }}</span>
            </el-form-item>
            <el-form-item label="数量">
                <el-input-number
                    v-model="orderForm.quantity"
                    :min="1"
                    @change="calculateTotalPrice"
                />
            </el-form-item>
            <el-form-item label="总价格">
                <span>{{ orderForm.totalPrice }}</span>
            </el-form-item>
            <el-form-item label="订单状态">
                <span>{{ orderForm.orderStatus === 0? '未支付' : (orderForm.orderStatus === 1? '已支付' : '已取消') }}</span>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="danger" @click="handleCancelOrder">取消订单</el-button>
            <el-button type="primary" @click="handleConfirmPurchase">确认购买</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTextbook, getTextbook, delTextbook, addTextbook, updateTextbook } from "@/api/manage/textbook";
import { listReview } from "@/api/manage/review";
import {  createOrder } from "@/api/manage/order";

export default {
  name: "Textbook",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教材列表表格数据
      textbookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        textbookName: null,
        isOnSale: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        textbookName: [
          { required: true, message: "教材名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "教材价格不能为空", trigger: "blur" }
        ],
      },
      // 当前教材ID
      currentTextbookId: null,
      // 当前教材名称
      currentTextbookName: null,
      // 评论数据
      reviews: [],
      // 查看评论对话框显示状态
      reviewDialogVisible: false,
      // 订单详情对话框显示状态（新增）
      orderDialogVisible: false,
        // 订单表单数据（新增，用于存储订单相关信息，如教材信息、数量、总价等）
        orderForm: {
            id: null,
            coverImage: null,
            textbookName: null,
            quantity: 1,
            totalPrice: 0,
            orderStatus: 0,
            textbookId: null,
            price: 0
        }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 取消订单操作 */
    handleCancelOrder() {
        this.orderDialogVisible = false;
    },
    /** 确认购买操作 */
    handleConfirmPurchase() {
      this.orderDialogVisible = false;
      const orderData = {
        textbookId: this.orderForm.textbookId,
        quantity: this.orderForm.quantity,
        totalAmount: this.orderForm.totalPrice,
        orderStatus: 0 // 初始设置为未支付状态
      };
      createOrder(orderData).then(() => {
        this.$modal.msgSuccess("订单创建成功");
        this.initAlipayPayment(this.orderForm.id);
      });
    },
    /** 初始化支付宝支付 */
    initAlipayPayment(orderId) {
      const paymentData = {
        orderId: orderId,
        totalAmount: this.orderForm.totalPrice,
        subject: this.orderForm.textbookName,
        body: "购买教材"
      };
      initAlipayPayment(paymentData).then(response => {
        const form = document.createElement("form");
        form.method = "post";
        form.action = response.data;
        document.body.appendChild(form);
        form.submit();
      });
    },

    /** 计算总价格 */
    calculateTotalPrice() {
    this.orderForm.totalPrice = this.orderForm.price * this.orderForm.quantity;
    },
    /** 购买按钮操作 */
    handleBuy(row) {
        // 重置 orderForm 的相关字段
        this.orderForm = {
          id: null,
          coverImage: null,
          textbookName: null,
          quantity: 1,
          totalPrice: 0,
          orderStatus: 0,
          textbookId: null,
          price: 0
        };
        this.orderForm.textbookId = row.id;
        this.orderForm.textbookName = row.textbookName;
        this.orderForm.coverImage = row.coverImage;
        this.orderForm.price = row.price;
        this.orderForm.totalPrice = row.price; // 初始总价等于单价（数量默认为1）
        this.orderDialogVisible = true;
    },
     /** 查看评论按钮操作 */
     handleViewReviews(row) {
      this.currentTextbookId = row.id;
      this.currentTextbookName = row.textbookName; // 存储教材名称
      this.getReviews(row.id); // 传递 row.id 而不是 scope.row
      this.reviewDialogVisible = true;
    },
    /** 获取评论数据 */
    getReviews(textbookId) { // 修改为接受 textbookId 参数
      listReview({
        pageNum: 1,
        pageSize: 10000,
        textbookId: textbookId, // 使用传递的 textbookId 参数
      }).then(response => {
        this.reviews = response.rows;
      });
    },
    /** 查询教材列表列表 */
    getList() {
      this.loading = true;
      listTextbook(this.queryParams).then(response => {
        this.textbookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        textbookName: null,
        author: null,
        publisher: null,
        price: null,
        textbookType: null,
        introduction: null,
        coverImage: null,
        isOnSale: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教材列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTextbook(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改教材列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTextbook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTextbook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除教材列表编号为"' + ids + '"的数据项？').then(function() {
        return delTextbook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/textbook/export', {
        ...this.queryParams
      }, `textbook_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
